const express = require('express');
const axios = require('axios');
const { getBeijingTime } = require('../utils/timeUtils');
const { getToken } = require('../utils/Getcookie');
const { flowdata } = require('../utils/flowquery');
const { newFlowdata, processNewDataFormat, getTrafficDetails } = require('../utils/newFlowquery');
const {trafficDetailQueries } = require('../database/queries');
const router = express.Router();

// 获取token接口
router.post('/get-token', async (req, res) => {
  try {
    const { operator, phone, code, appid } = req.body;
    const result = await getToken({
    mobile: phone,
    smscode: code,
    appId:  appid
  });
  // console.log(result)
    // 模拟调用第三方接口获取token
    // 实际项目中这里应该调用真实的第三方接口
    let mockResponse = {
      success: true,
      token: `mock_token_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
      expires: Date.now() + 24 * 60 * 60 * 1000  // 24小时后过期
    };

    if(result.success){
        mockResponse = {
        success: true,
        token: result.data.cookie,
        expires: Date.now() + 24 * 60 * 60 * 1000*30000 // 24小时后过期
      }
  };
   

    // 模拟网络延迟
    await new Promise(resolve => setTimeout(resolve, 1000));

    res.json({
      success: true,
      message: 'Token获取成功',
      data: mockResponse
    });
  } catch (error) {
    console.error('获取Token错误:', error);
    res.status(500).json({
      success: false,
      message: '获取Token失败'
    });
  }
});

// 模拟第三方流量数据接口
router.post('/traffic-data', async (req, res) => {
  try {
    const { token, phone, operator, appId,configId,config } = req.body;
    const Resdata=await flowdata(token)
    const latestTraffic = await trafficDetailQueries.findLatestByConfigId(configId);
    // console.log(JSON.stringify(latestTraffic));
    // 验证token（模拟）
    // if (!token || !token.startsWith('mock_token_')) {
    //   return res.status(401).json({
    //     success: false,
    //     message: 'Token无效'
    //   });
    // }
   

    // 模拟生成流量数据
    let generalTotal = 40960; // 40GB通用流量
    let directedTotal = 5120; // 5GB定向流量
    let publicFree = 5.14; // 公免流量
    
    let generalUsed = 4232.63 + Math.random() * 100; // 已用通用流量
    let generalRemaining = generalTotal - generalUsed;  //通用流量剩余流量
    
    let directedUsed = 146381.24 + Math.random() * 1000; // 已用定向流量（可能超套餐）
    let directedRemaining = Math.max(0, directedTotal - directedUsed); //通用流量剩余流量
    
    let totalTraffic = (generalTotal + directedTotal) / 1024; // 转换为GB   总流量
    let usedTraffic = (generalUsed + directedUsed) / 1024;     //总用流量
    let remainingTraffic = (generalRemaining + directedRemaining) / 1024;     //总剩流量
    
    let jumpPoints = Math.floor(100 + Math.random() * 100); // 100-200之间的跳点  //跳点
    let Freeflow = 5.14; // 免流

   if (Resdata.flowSumList) {
        // console.log(JSON.stringify(Resdata));
        
        // 检查数组元素是否存在，不存在则使用默认对象
        const generalItem = Resdata.flowSumList[0] || { xcanusevalue: 0, xusedvalue: 0 };
        const directedItem = Resdata.flowSumList[1] || { xcanusevalue: 0, xusedvalue: 0 };
        const publicItem = Resdata.flowSumList[2] || { xcanusevalue: 0, xusedvalue: 0 };
        
        // 使用安全获取到的元素进行计算
        generalTotal = Number(generalItem.xcanusevalue) + Number(generalItem.xusedvalue);
        directedTotal = Number(directedItem.xcanusevalue) + Number(directedItem.xusedvalue);
        publicFree = Number(publicItem.xusedvalue);

        generalUsed = Number(generalItem.xusedvalue);
        generalRemaining = Number(generalItem.xcanusevalue);
        
        directedUsed = Number(directedItem.xusedvalue);
        directedRemaining = Number(directedItem.xcanusevalue);

        totalTraffic = (generalTotal + directedTotal) / 1024; // 转换为GB 总流量
        usedTraffic = (generalUsed + directedUsed) / 1024;    // 总用流量
        remainingTraffic = (generalRemaining + directedRemaining) / 1024; // 总剩流量

        // 处理 latestTraffic 相关计算
        const latestGeneralUsed = latestTraffic ? Number(latestTraffic.general_used || 0) : 0;
        jumpPoints = parseFloat((generalUsed - latestGeneralUsed).toFixed(2));
        
        const latestdirectedUsed = latestTraffic ? Number(latestTraffic.directed_used || 0) : 0;
        Freeflow = parseFloat((directedUsed - latestdirectedUsed).toFixed(2));
      }

    const trafficData = {
      totalTraffic: parseFloat(totalTraffic.toFixed(2)),
      usedTraffic: parseFloat(usedTraffic.toFixed(2)),
      remainingTraffic: parseFloat(remainingTraffic.toFixed(2)),
      generalUsed: parseFloat(generalUsed.toFixed(2)),
      generalRemaining: parseFloat(generalRemaining.toFixed(2)),
      generalTotal: parseFloat(generalTotal.toFixed(2)),
      directedUsed: parseFloat(directedUsed.toFixed(2)),
      directedRemaining: parseFloat(directedRemaining.toFixed(2)),
      directedTotal: parseFloat(directedTotal.toFixed(2)),
      publicFree: parseFloat(publicFree.toFixed(2)),
      jumpPoints,
      Freeflow,
      queryTime: getBeijingTime(),
      operator,
      packageName:Resdata.packageName || "未知",
      phone: phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2') // 隐藏手机号中间4位
    };

    // 模拟网络延迟
    await new Promise(resolve => setTimeout(resolve, 500));

    res.json({
      success: true,
      message: '流量数据获取成功',
      data: trafficData
    });
  } catch (error) {
    console.error('获取流量数据错误:', error);
    res.status(500).json({
      success: false,
      message: '获取流量数据失败'
    });
  }
});

// 新的第三方流量数据接口
router.post('/new-traffic-data', async (req, res) => {
  try {
    const { token, phone, operator, appId, configId, config } = req.body;
    
    // 调用新的流量数据查询接口
    const Resdata = await newFlowdata(token);
    const latestTraffic = await trafficDetailQueries.findLatestByConfigId(configId);
    
    // 处理新的数据格式
    let generalTotal = 0;
    let generalUsed = 0;
    let generalRemaining = 0;
    let directedTotal = 0;
    let directedUsed = 0;
    let directedRemaining = 0;
    let publicFree = 0;
    let voiceTotal = 0;
    let voiceUsed = 0;
    let voiceRemaining = 0;
    
    if (Resdata.flowSumList) {
      // 使用新格式的数据
      const generalItem = Resdata.flowSumList[0] || { xcanusevalue: 0, xusedvalue: 0 };
      const directedItem = Resdata.flowSumList[1] || { xcanusevalue: 0, xusedvalue: 0 };
      const publicItem = Resdata.flowSumList[2] || { xcanusevalue: 0, xusedvalue: 0 };
      
      generalTotal = Number(generalItem.xcanusevalue) + Number(generalItem.xusedvalue);
      directedTotal = Number(directedItem.xcanusevalue) + Number(directedItem.xusedvalue);
      publicFree = Number(publicItem.xusedvalue);

      generalUsed = Number(generalItem.xusedvalue);
      generalRemaining = Number(generalItem.xcanusevalue);
      
      directedUsed = Number(directedItem.xusedvalue);
      directedRemaining = Number(directedItem.xcanusevalue);
      
      // 语音数据
      if (Resdata.voiceData) {
        voiceTotal = Resdata.voiceData.total;
        voiceUsed = Resdata.voiceData.used;
        voiceRemaining = Resdata.voiceData.remaining;
      }
    }
    
    // 计算总流量
    let totalTraffic = (generalTotal + directedTotal) / 1024; // 转换为GB
    let usedTraffic = (generalUsed + directedUsed) / 1024;    // 总用流量
    let remainingTraffic = (generalRemaining + directedRemaining) / 1024; // 总剩流量
    
    // 计算跳点和免流
    let jumpPoints = 0;
    let Freeflow = 0;
    
    if (latestTraffic) {
      const latestGeneralUsed = Number(latestTraffic.general_used || 0);
      jumpPoints = parseFloat((generalUsed - latestGeneralUsed).toFixed(2));
      
      const latestdirectedUsed = Number(latestTraffic.directed_used || 0);
      Freeflow = parseFloat((directedUsed - latestdirectedUsed).toFixed(2));
    }
    
    // 构建返回数据
    const trafficData = {
      totalTraffic: parseFloat(totalTraffic.toFixed(2)),
      usedTraffic: parseFloat(usedTraffic.toFixed(2)),
      remainingTraffic: parseFloat(remainingTraffic.toFixed(2)),
      generalUsed: parseFloat(generalUsed.toFixed(2)),
      generalRemaining: parseFloat(generalRemaining.toFixed(2)),
      generalTotal: parseFloat(generalTotal.toFixed(2)),
      directedUsed: parseFloat(directedUsed.toFixed(2)),
      directedRemaining: parseFloat(directedRemaining.toFixed(2)),
      directedTotal: parseFloat(directedTotal.toFixed(2)),
      publicFree: parseFloat(publicFree.toFixed(2)),
      jumpPoints,
      Freeflow,
      queryTime: getBeijingTime(),
      operator,
      packageName: Resdata.packageName || "未知",
      phone: phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2'), // 隐藏手机号中间4位
      // 新增字段
      voiceData: {
        total: voiceTotal,
        used: voiceUsed,
        remaining: voiceRemaining
      },
      // 详细数据
      detailedData: Resdata.detailedData || null,
      // 流量详情（兼容旧格式）
      trafficDetails: getTrafficDetails(Resdata.originalData),
      // 数据源标识
      dataSource: 'new-api'
    };

    // 模拟网络延迟
    await new Promise(resolve => setTimeout(resolve, 500));

    res.json({
      success: true,
      message: '新流量数据获取成功',
      data: trafficData
    });
  } catch (error) {
    console.error('获取新流量数据错误:', error);
    res.status(500).json({
      success: false,
      message: '获取新流量数据失败'
    });
  }
});

module.exports = router;
